package at.ac.tuwien.swa.sparrow.client

import ac.at.tuwien.infosys.swa.audio.{Fingerprint, FingerprintSystem}
import at.ac.tuwien.swa.sparrow._
import at.ac.tuwien.swa.sparrow.common.{InProgress, TrackResult}
import at.ac.tuwien.swa.sparrow.server.ClientService
import java.io.File
import javax.inject.Inject
import javax.sound.sampled.AudioSystem
import org.springframework.context.annotation.{AnnotationConfigApplicationContext, Bean, Configuration}
import org.springframework.core.io.ClassPathResource
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean
import scala.annotation.tailrec

object TestClient extends App {
	@Inject var service: ClientService = _
	@Inject var fun: (File) => Fingerprint = _

	val ctx = new AnnotationConfigApplicationContext(classOf[SpringConfig])
	ctx.getAutowireCapableBeanFactory autowireBean this

	val authToken = service.login("demo", "secret")
	println(s"You have ${service.buy(10)} credits now.")

	val ticket = service.request(authToken, fun(new ClassPathResource("music/Armenia.mp3").getFile))
	println("Got ticket " + ticket.id)

	val result = waitForResult
	println(result.state + ": " + result.trackInfo)

	service.logout()

	@tailrec def waitForResult: TrackResult = {
		service.result(ticket.id) match {
			case TrackResult(_, InProgress) => Thread sleep 1000; waitForResult
			case t: TrackResult => t
		}
	}
}

@Configuration
class SpringConfig {
	@Bean def clientService = {
		val factoryBean = new HttpInvokerProxyFactoryBean
		factoryBean.setServiceUrl(s"${SERVICE_URL dropRight 4}client")
		factoryBean.setServiceInterface(classOf[ClientService])
		factoryBean.afterPropertiesSet()
		factoryBean.getObject.asInstanceOf[ClientService]
	}

	@Bean def audioFingerprintFunction = (f: File) => FingerprintSystem fingerprint (AudioSystem getAudioInputStream f)
}
